//
//  PresentChatViewController.m
//  IMMantisSDK_Example
//
//  Created by 陈志亮 on 2021/4/1.
//  Copyright © 2021 chenzhiliang. All rights reserved.
//

#import "PresentChatViewController.h"
#import "MantisLeaveMessageViewController.h"
#import "ShowMessageViewController.h"
#import "PhotoShowViewController.h"

#import "MartinsNewInputView.h"
#import <WebKit/WebKit.h>
#import "ChatNavView.h"


#import "MantisLeftTextTableViewCell.h"//左边带文字cell
#import "MaintsAcademicTableViewCell.h"//学历cell
#import "MantisRightTextTableViewCell.h"//右边带文字cell
#import "MantisRightImgTableViewCell.h"//图片cell
#import "MantisSystemTableViewCell.h"//系统消息cell
#import "MantisRightAcademicTableViewCell.h"//可选性消息cell
#import "MantisLeftImgTableViewCell.h"//左边图片cell
#import "MantisWebTableViewCell.h"//左边webviewcell
#import "RichTextTableViewCell.h"//富文本消息cell
#import "MantisRightRichTextTableViewCell.h"//富文本右侧消息

#import "UploadRequstTaskTool.h"
#import "IQKeyboardManager.h"
#import "MantisCheckNetTool.h"
#import "MantisGCDTimer.h"



#import "ManitsFileResultModel.h"
#import "AcademicJsonModel.h"
#import "ChatHandleCommonLogic.h"
#import "SendLogicHandle.h"
#import "MantisCellJosonData.h"
#import "ReceiveLogicHandle.h"
#import "CommonHeader.h"




static CGFloat inputViewHeight=52;//输入框高度
static NSInteger askCount=30;//输入次数
static NSInteger isNeedDelay=0;//未收到消息需要延迟,收到消息以后就不用延迟了
#define viewBgColor [UIColor jk_colorWithHexString:@"#F5F8FA"]

@interface PresentChatViewController ()<UITableViewDelegate,UITableViewDataSource,UIGestureRecognizerDelegate>
@property(nonatomic,strong)UIView*chatView;//聊天内容背景
@property(nonatomic,strong)UITableView*tableView;
@property(nonatomic,strong)NSMutableArray*dataArr;
@property(nonatomic,strong)MartinsNewInputView*inputView;
@property(nonatomic,assign)CGFloat keyBoardHeight;//键盘高度
@property(nonatomic,strong)NSMutableArray*welComesArr;
@property(nonatomic,copy)NSString*obserVerisAsk;//观察是否需要向机器人拉取追问
@property(nonatomic,strong)NSMutableArray*timerArr;//存放定时器的数组
@property(nonatomic,assign)BOOL userIsInputing;//用户是否正在输入
@property(nonatomic,assign)BOOL isBall;//标记球是否在访客手中
@property(nonatomic,assign)NSTimeInterval endEditTimer;//记录编辑结束时间
@property(nonatomic,copy)NSString*isCancleWelcome;//是否取消欢迎语 1为取消
@property(nonatomic,strong)NSTimer*myTimer;
@property(nonatomic,strong)WelcomeJsonData*buildModel;//建立连接
@property(nonatomic,strong)MatinsIMinitModel*myModel;//初始化数据
@property(nonatomic,strong)ConnectConfigModel*configModel;//配置模型
@property(nonatomic,assign)BOOL isHasJump;//标记是否已经跳转
@property(nonatomic,assign)BOOL isCompete;//没有网络
@property(nonatomic,strong)NSMutableArray*historyArr;//记录历史消息数组
@property(nonatomic,strong)ShowMessageViewController*showVC;//弹出显示
@property(nonatomic,strong)ShowMessageViewController*showNetVC;//网络弹窗
@property(nonatomic,copy)NSString*avaterURL;//头像地址
@property(nonatomic,strong)UILabel*headView;//头部视图
@property(nonatomic,strong)UIView*blackView;
@property(nonatomic,strong)ChatNavView*navView;//自定义导航
@property(nonatomic,assign)float screenRate;
@end

@implementation PresentChatViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.frame =CGRectMake(0, 0, IMSCREEN_WIDTH, IMSCREEN_HEIGHT-IMKsafeAreaBottom);
    [self setUpView];
    [self getLatestProbeData];//获取最新探头信息
}


-(void)setUpView{
    //黑色背景
    UIView*blackView = [[UIView alloc]initWithFrame:self.view.frame];
    self.blackView= blackView;
    blackView.backgroundColor =[UIColor jk_colorWithHexString:@"#FF14181A"];//FF14181A
    blackView.userInteractionEnabled=YES;
    blackView.alpha=0.5;
    [self.view addSubview:blackView];
    UITapGestureRecognizer*tapVC = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(dismissFromParentVC)];
    tapVC.delegate=self;
    [self.view addGestureRecognizer:tapVC];
    
    //聊天界面背景
    UIView*chatView = [[UIView alloc]initWithFrame:CGRectMake(0, self.view.jk_height*(1-self.screenRate), self.view.jk_width, (self.view.jk_height*self.screenRate))];
    self.chatView=chatView;
    chatView.backgroundColor =viewBgColor;
    [self.view addSubview:chatView];
    //导航页面
    [self creatNavView:chatView];
    //tableview和输入框
    [self initView:chatView];
}

-(void)initView:(UIView*)chatView{
    isNeedDelay=0;
    [self creaTableView];
    [self creatInputView];
    WS(weakSelf);
    __block  int k=0;
    [MantisCheckNetTool CheckisHasNet:^(NSString * _Nonnull isHasNet) {
        BOOL isHas=isHasNet.boolValue;
        if (!isHas) {
            if (k==0) {
                ShowMessageViewController *showVC = [[ShowMessageViewController alloc]initWithArr:@[@"确定"]];
                weakSelf.showNetVC=showVC;
                showVC.messageLabel.text=@"没有网络，建立连接失败，请检查网络";
                showVC.cancleBlock = ^{
                    [weakSelf.showNetVC dismissFromParentVC];
                    [weakSelf.navigationController popViewControllerAnimated:YES];
                };
                [showVC showCurrentVC:weakSelf.navigationController];
            }else{
                if ([weakSelf.inputView.textField isFirstResponder]) {
                    [weakSelf.inputView.textField resignFirstResponder];
                }
                [weakSelf.chatView nlShowHudText:@"没有网络，请检查网络" hideDelay:2.0 completionBlock:nil];
            }
        }else{
            if ([weakSelf.inputView.textField isFirstResponder]) {
                [weakSelf.inputView.textField resignFirstResponder];
            }
            if (k==0) {
                [weakSelf initBuildConnect];//第一次建立连接
            }
        }
        k++;
    }];
    
    self.isBall=YES;
}

-(void)addKnoticeAndObserver{
    [self registerForKeyboardNotifications];//键盘监听
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(getNoticeInfo:) name:kuserStartInputNotice object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(getNoticeInfo:) name:kuserDidInputNotice object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(retryNews:) name:KnoticeRetryNewsSend object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(loginSucess:) name:KnoticeLoginSucess object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(loginFail:) name:KnoticeLoginFail object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(getModelNotice:) name:KnoticeWebLoadFinish object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(showHiddenoodView:) name:KnoticeDeLayThreeSeconds object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(getNewsNotice:) name:KnoticeReceiveNewMsgs object:nil];
    
}
//MARK:拿到腾讯云消息以后的通知
-(void)getNewsNotice:(NSNotification*)notice{
    NSDictionary*dic=notice.userInfo;
    if (dic.allKeys.count>1) {
        NSArray*arr = dic[@"msgs"];
        MatinsIMinitModel*myModel =dic[@"myModel"];
        ConnectConfigModel*configmodel=dic[@"configmodel"];
        
        [self hasReceiveNewMessage:arr withMyModel:myModel withConfig:configmodel];
    }
    NSString*status =dic[@"status"];
    [self hasReceiveUserStautsChange:status];
    
}

-(void)initBuildConnect{
    
    [self setLoadingAnimationFrame:self.chatView.frame imgArr:self.imgArr];//转圈
    
    self.loadingView.contentLB.text=self.loadingText.length>0?self.loadingText:  @"正在与客服建立连接";
    
    [[IQKeyboardManager sharedManager]setEnableAutoToolbar:NO];
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside=YES;
    
    MantisSDKTool*tool = [MantisSDKTool keyManitsSDKTool];
    MatinsIMinitModel*myModel=tool.myModel;//初始化数据
    self.myModel=myModel;
    NSString*userSig = tool.userSig;
    [tool loginTecentIm:myModel.uuidStr userSig:userSig];//直接连接
    [self addKnoticeAndObserver];
    self.endEditTimer=0;
}

//接收用户输入文字编辑状态的通知包括：开始、已经编辑、结束编辑
-(void)getNoticeInfo:(NSNotification*)notice{
    NSString*noticeName=notice.name;
    if ([noticeName isEqualToString:kuserStartInputNotice]) {
        
    }else if ([noticeName isEqualToString:kuserDidInputNotice]){
        NSTimeInterval nowTimer=[[NSString jk_UUIDTimestamp]doubleValue];;
        if (nowTimer-self.endEditTimer>200) {
            [self prereadNews];//给后台发送预读消息
        }
        self.endEditTimer=nowTimer;
    }
}
//MARK:初始化View
-(void)creatNavView:(UIView*)chatView{
    WS(weakSelf);
    ChatNavView*navView = [[ChatNavView alloc]initWithFrame:CGRectMake(0, 0, self.chatView.jk_width, kImNavigationBarHeight)];
    weakSelf.navView =navView;
    [navView.backBtn addTarget:weakSelf action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
    [chatView addSubview:navView];
    [self.navView reloadNavView:self.probeModel];
    
}

-(void)creaTableView{
    UITableView*tableView = [[UITableView alloc]initWithFrame:CGRectMake(0,self.navView.jk_height, self.view.jk_width, self.chatView.jk_height-inputViewHeight-self.navView.jk_height)];
    self.tableView=tableView;
    tableView.backgroundColor=viewBgColor;
    tableView.separatorStyle=0;
    tableView.dataSource=self;
    tableView.delegate=self;
    tableView.estimatedRowHeight=100;
    [self.chatView addSubview:tableView];
    
    UILabel*headView =[[UILabel alloc]initWithFrame:CGRectMake(0, 0, self.view.jk_width, adaptWidth750(60*0.7))];
    self.headView=headView;
    headView.backgroundColor=viewBgColor;
    headView.font =KIMFontRegularSize(14*0.7);
    headView.textColor=[UIColor jk_colorWithHexString:@"#C9D1D4"];
    headView.textAlignment=NSTextAlignmentCenter;
    
    [self.chatView addSubview:headView];
    tableView.tableHeaderView=headView;
}
//MARK:底部输入框
-(void)creatInputView{
    MartinsNewInputView*inputView= [[MartinsNewInputView alloc]initWithFrame:CGRectMake(0,self.tableView.jk_bottom, IMSCREEN_WIDTH, inputViewHeight)];
    self.inputView=inputView;
    [self.chatView addSubview:inputView];
    [self.inputView reloadSendView:self.probeModel];
    
    WS(weakSelf);
    inputView.callBackStr = ^(NSString * _Nonnull str) {
        MantisCellJosonData*cellJosonData=[SendComLogicHandle sendMessagePrepareWithCellJosnData:SDK_MSG by:vendor1Str];//外层model
        
        MantisTextCellConetentData*contentModel=[SendComLogicHandle getCellContenModelFromBuildModel:weakSelf.buildModel proModel:weakSelf.myModel type:@"text"];//内层消息model
        contentModel.msg=str;//给后台用的
        cellJosonData.content=contentModel;
        
        MantisTextCellData *cellData=[SendComLogicHandle getCellDataFrom:str json:cellJosonData];//添加自定义消息类型
        cellData.isHasEmoji=YES;
        NSString*richStr=weakSelf.inputView.textField.plainString;
        richStr=[richStr stringByReplacingOccurrencesOfString:@"[em" withString:@""];
        cellData.contentRichStr=richStr;//前段显示只是为了计算文本大小
        cellData.inputStr = [weakSelf.inputView changeMessage:weakSelf.inputView.textField.plainString];//前段显示文字表情用
        [weakSelf.inputView clearAllText:weakSelf.inputView];
        [weakSelf sendChatMesageAndUpdateView:cellData];//发送消息
        
    };
    
    inputView.photoBlock = ^{
        PhotoCropManager *manager =[PhotoCropManager photoCropSharedManager];
        manager.baseVC=weakSelf;
        [manager chosePhotoFromAsset:NO];
        manager.resultBlock = ^(NSString *imgStr, UIImage *img) {
            [weakSelf.chatView nlShowHudLoadingWithText:@"正在上传图片,请稍等"];
            NSMutableDictionary*param =[NSMutableDictionary new];
            param[@"companyId"]= weakSelf.myModel.companyId;
            param[@"vistorId"]= weakSelf.buildModel.payload.agentId;
            [UploadRequstTaskTool uploadWithPictures:img andMethod:@"" params:param andDomainName:@"" onProgressBlock:^(NSProgress * _Nonnull uploadProgress) {
                
                
            } onSuccessBlock:^(id data, NSURLSessionDataTask *task) {
                [weakSelf.chatView nlHideHudLoading];
                [weakSelf sendPicMessage:data img:img];//发送图片消息
            } onFailBlock:^(NSError *error, NSURLSessionTask *task) {
                [weakSelf.chatView nlHideHudLoading];
                [weakSelf.chatView nlShowHudText:@"上传图片失败" hideDelay:2.0 completionBlock:nil];
                NSDictionary*dic=[NSDictionary new];
                [weakSelf sendPicMessage:dic img:img];//发送图片消息
            }];
            
        };
        
    };
}
//发送图片消息
-(void)sendPicMessage:(id)data img:(UIImage *)img{
    WS(weakSelf);
    MantisImageMessageCellData*cellData=[SendComLogicHandle getPicMessagefromchatModel:weakSelf.buildModel myModel:weakSelf.myModel picData:data];
    cellData.photoImg=img;
    [weakSelf sendChatMesageAndUpdateView:cellData];//发送图片消息
}
//MARK:键盘监听
- (void) registerForKeyboardNotifications
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShown:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter]  addObserver:self selector:@selector(keyboardWillHidden:) name:UIKeyboardWillHideNotification object:nil];
}
- (void)keyboardWillShown:(NSNotification *) notif
{
    WS(weakSelf);
    NSDictionary *info = [notif userInfo];
    NSLog(@"keyboardWillShown:%@",info);
    
    NSValue *value = [info objectForKey:UIKeyboardFrameBeginUserInfoKey];
    CGRect beginRect=value.CGRectValue;
    
    NSValue *endValue1 = [info objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect endRect=endValue1.CGRectValue;
    
    CGSize keyboardSize =endRect.size;
    NSLog(@"ShowkeyBoard:%f", keyboardSize.height);
    int height=endRect.size.height-beginRect.size.height;
    self.keyBoardHeight=endRect.origin.y;
    NSLog(@"+++++%f",self.keyBoardHeight);
    [UIView animateWithDuration:0.2 animations:^{
        weakSelf.chatView.frame =CGRectMake(0, 0, weakSelf.view.jk_width, weakSelf.view.jk_height);
        
        [weakSelf changeTableViewHeight:weakSelf.keyBoardHeight];
        
        weakSelf.inputView.frame=CGRectMake(0,weakSelf.tableView.jk_bottom, weakSelf.inputView.jk_width, weakSelf.inputView.jk_height);
        
    }];
    
}

- (void)keyboardWillHidden:(NSNotification *) notif
{
    WS(weakSelf);
    NSDictionary *info = [notif userInfo];
    NSLog(@"keyboardWillHidden:%@",info);
    NSValue *endValue1 = [info objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect endRect=endValue1.CGRectValue;
    
    CGSize keyboardSize =endRect.size;
    NSLog(@"ShowkeyBoard:%f", keyboardSize.height);
    self.keyBoardHeight=endRect.origin.y;
    [UIView animateWithDuration:0.2 animations:^{
        weakSelf.chatView.frame=   CGRectMake(0, weakSelf.view.jk_height*(1-weakSelf.screenRate), weakSelf.view.jk_width, weakSelf.view.jk_height*weakSelf.screenRate);
        weakSelf.tableView.frame =CGRectMake(weakSelf.chatView.origin.x, weakSelf.navView.jk_bottom, weakSelf.chatView.jk_width, weakSelf.chatView.jk_height-weakSelf.navView.jk_height-weakSelf.inputView.jk_height);
        [weakSelf updateTableView];
        weakSelf. inputView.frame=CGRectMake(0,weakSelf.tableView.jk_bottom, weakSelf.inputView.jk_width, weakSelf.inputView.jk_height);
        
    }];
}
//MARK:tableViewData和代理
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    MantisCellBaseModel *data = self.dataArr[indexPath.row];
    
    CGFloat lineSpace =adaptWidth750(120);
    return data.contentSize.height+lineSpace;
    
    
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArr.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    WS(weakSelf);
    MantisCellBaseModel* data = self.dataArr[indexPath.row];
    data.indexPath=indexPath;
    if ([data isKindOfClass:[MantisTextCellData class]]) {
        MantisTextCellData*newData=(MantisTextCellData*)data;
        if (newData.isMyself) {
            MantisRightTextTableViewCell*myCell = [[MantisRightTextTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"FirstMyCell"];
            [myCell reloadCellModel:newData];
            
            return myCell;
        }else{
            MantisLeftTextTableViewCell *myCell = [[MantisLeftTextTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ScecondMyCell"];
            [myCell reloadCellModel:newData];
            
            return myCell;
        }
        
    }else if ([data isKindOfClass:[MantisAcademicCellData class]]){
        MantisAcademicCellData*newData=(MantisAcademicCellData*)data;
        MaintsAcademicTableViewCell*myCell = [[MaintsAcademicTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ThirdMyCell"];
        [myCell reloadCellModel:newData];
        myCell.btnTitleBlock = ^(MantisTextCellSubContentData*btnData) {
            newData.content.isHidden=YES;
            newData.historyModel=[WelcomeJsonhistoryMsgData new];
            [weakSelf.dataArr replaceObjectAtIndex:indexPath.row withObject:newData];
            [weakSelf.tableView reloadData];
            MantisCellJosonData*cellJosonData=[SendComLogicHandle sendMessagePrepareWithCellJosnData:SDK_MSG by:vendor1Str];//组装外层消息
            
            AcademicJsonModel*jsonModel =[AcademicJsonModel new];
            jsonModel.displayMsg=btnData.label;
            jsonModel.btnId=btnData.btnId;
            
            
            MantisTextCellConetentData*contentModel=[SendComLogicHandle getCellContenModelFromBuildModel:weakSelf.buildModel proModel:weakSelf.myModel type:@"text"];//组装外层json消息
            contentModel.msg=jsonModel.mj_JSONString;
            cellJosonData.content=contentModel;
            
            MantisTextCellSubContentData *cellData = [SendComLogicHandle getChoiceCellDataFrom:btnData json:cellJosonData];
            
            [self sendChatMesageAndUpdateView:cellData];
        };
        return myCell;
    }else if ([data isKindOfClass:[MantisImageMessageCellData class]]){
        MantisImageMessageCellData*newData=(MantisImageMessageCellData*)data;
        if (newData.isMyself) {
            MantisRightImgTableViewCell*myCell = [[MantisRightImgTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"FourthMyCell"];
            [myCell reloadCellModel:newData];
            return myCell;
        }else{
            
            MantisLeftImgTableViewCell*myCell = [[MantisLeftImgTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"FourthMyCell"];
            [myCell reloadCellModel:newData];
            return myCell;
        }
        
        
    }else if ([data isKindOfClass:[MantisSystemModel class]]){
        MantisSystemModel*newData=(MantisSystemModel*)data;
        MantisSystemTableViewCell*myCell = [[MantisSystemTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"FifthMyCell"];
        [myCell reloadCellModel:newData];
        return myCell;
    }else if ([data isKindOfClass:[MantisTextCellSubContentData class]]){
        MantisTextCellSubContentData*newData=(MantisTextCellSubContentData*)data;
        MantisRightAcademicTableViewCell*myCell = [[MantisRightAcademicTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"SixthMyCell"];
        [myCell reloadCellModel:newData];
        return myCell;
    }else if ([data isKindOfClass:[MantisWelcomeImgModel class]]){
        MantisWelcomeImgModel*newData=(MantisWelcomeImgModel*)data;
        MantisWebTableViewCell*myCell = [[MantisWebTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"SeventhMyCell"];
        if ([newData.historyModel.msg containsString:@"additionMsg"]) {
            [myCell.contentView addSubview:newData.wkWebView];
            [myCell reloadWebViewWith:newData];
            myCell.choseBtnView.btnTitleBlock = ^(MantisTextCellSubContentData * _Nonnull btnData) {
                newData.isHidden=YES;
                newData.historyModel=[WelcomeJsonhistoryMsgData new];
                [weakSelf.dataArr replaceObjectAtIndex:indexPath.row withObject:newData];
                [weakSelf.tableView reloadData];
                MantisCellJosonData*cellJosonData=[SendComLogicHandle sendMessagePrepareWithCellJosnData:SDK_MSG by:vendor1Str];//组装外层消息
                
                AcademicJsonModel*jsonModel =[AcademicJsonModel new];
                jsonModel.displayMsg=btnData.label;
                jsonModel.btnId=btnData.btnId;
                
                MantisTextCellConetentData*contentModel=[SendComLogicHandle getCellContenModelFromBuildModel:weakSelf.buildModel proModel:weakSelf.myModel type:@"text"];//组装外层json消息
                contentModel.msg=jsonModel.mj_JSONString;
                cellJosonData.content=contentModel;
                
                MantisTextCellSubContentData *cellData = [SendComLogicHandle getChoiceCellDataFrom:btnData json:cellJosonData];
                [self sendChatMesageAndUpdateView:cellData];
            };
            
        }else
        {
            [myCell.contentView addSubview:newData.wkWebView];
        }
        
        [myCell reloadCellModel:newData];
        
        return myCell;
    }else if ([data isKindOfClass:[MantisRichTextModel class]]){
        MantisRichTextModel*newData=(MantisRichTextModel*)data;
        if (newData.isMyself) {
            MantisRightRichTextTableViewCell*myCell = [[MantisRightRichTextTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"EightthMyCell"];
            [myCell reloadCellModel:newData];
            return myCell;
        }else{
            RichTextTableViewCell*myCell = [[RichTextTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"NinethMyCell"];
            [myCell reloadCellModel:newData];
            return myCell;
        }
        
        
    }
    return nil;
}
-(void)getModelNotice:(NSNotification*)notice{
    [self.tableView reloadData];
    [self hiddenNetAndLoadingView];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    MantisCellBaseModel *data = self.dataArr[indexPath.row];
    if ([data isKindOfClass:[MantisImageMessageCellData class]]) {
        MantisImageMessageCellData*photoData=(MantisImageMessageCellData*)data;
        NSString*imgUrl;
        PhotoShowViewController*showVC = [PhotoShowViewController new];
        if (photoData.imgUrl.length>0) {
            imgUrl=photoData.imgUrl;
        }else if ([photoData.content containsString:@"src"]){
            imgUrl=photoData.content;
            imgUrl =[NSString getNewImgurlFromurl:imgUrl];
        }
        showVC.imgUrl=imgUrl;
        [showVC showCurrentVC:self.navigationController];
    }
    
}

-(void)firstUPdataTableView{
    if (self.dataArr.count==0||!self.dataArr.count) {
        return;
    }
    
    [[GetChatTime new]computeVisibleTimeAndRefreshTable:@"" dataArr:self.dataArr historyArr:self.historyArr];
    [self.tableView reloadData];
    [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.dataArr.count - 1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    [self hiddenNetAndLoadingView];
    
}
-(void)updateTableView{
    if (self.dataArr.count==0||!self.dataArr.count) {
        return;
    }
    [self.tableView reloadData];
    [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.dataArr.count - 1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}

//插入历史数据
-(void)refreshHistoryCellData{
    if (self.dataArr.count==0||!self.dataArr.count) {
        return;
    }
    self.dataArr=  [[GetChatTime new]computeVisibleTimeAndRefreshTable:@"" dataArr:self.dataArr historyArr:self.historyArr];
    [self.tableView reloadData];
    [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.dataArr.count - 1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    [self hiddenNetAndLoadingView];//停止转圈
}


-(NSMutableArray *)dataArr{
    if (!_dataArr) {
        _dataArr=[NSMutableArray new];
    }
    return _dataArr;
}

//改变tableview高度
-(void)changeTableViewHeight:(NSInteger)keyBoardHeight{
    CGRect orginalFrame=self.tableView.frame;
    self.tableView.frame =CGRectMake(orginalFrame.origin.x, self.navView.jk_height, orginalFrame.size.width,keyBoardHeight-self.navView.jk_height-inputViewHeight);
    if (self.dataArr.count>1) {
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.dataArr.count - 1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    }
}
//发送消息并显示数据
-(void)sendChatMesageAndUpdateView:(MantisCellBaseModel*)cellData{
    WS(weakSelf);
    cellData.sendTime=[[NSString jk_UUIDTimestamp]doubleValue];
    if ([weakSelf.dataArr containsObject:cellData]) {
        [weakSelf.dataArr removeObject:cellData];
    }
    [weakSelf.dataArr addObject:cellData];
    [weakSelf updateTableView];//更新view
    //发送消息
    
    [[GetChatTime new]computeVisibleTimeAndRefreshTable:@"" dataArr:weakSelf.dataArr historyArr:weakSelf.historyArr];
    
    [[SendLogicHandle keySendLoginHandle] sendChatMesage:cellData.innerMessage sucess:^{
        
    } fail:^(int code, NSString * _Nonnull msg) {
        if (code!=20006) {
            cellData.isShowError=YES;
            [weakSelf.dataArr replaceObjectAtIndex:cellData.indexPath.row withObject:cellData];
            [weakSelf.tableView reloadRowsAtIndexPaths:@[cellData.indexPath] withRowAnimation:UITableViewRowAnimationNone];
        }
    }];
    
    //延迟2s提示对方正在输入
    [MantisGCDTimer delayTime:2 withBlock:^{
        weakSelf.navView.backLabel.hidden=NO;
        weakSelf.navView.backLabel.text=@"对方正在输入...";
    }];
    weakSelf.isCancleWelcome=@"1";//是否取消欢迎语，1:取消发送 0:可以发送
    weakSelf.isBall=NO;//NO球不在访客手里  Yes球在访客手里
}

-(NSMutableArray *)welComesArr{
    if (!_welComesArr) {
        _welComesArr=[NSMutableArray new];
    }
    return _welComesArr;
}

//MARK:预读消息
-(void)prereadNews{
    WS(weakSelf);
    NSString*richStr = [weakSelf.inputView changeEmojiMessage:weakSelf.inputView.textField.plainString];
    richStr=[richStr stringByReplacingOccurrencesOfString:@"\"" withString:@"'"];
    
    [[SendLogicHandle keySendLoginHandle]sendPreReadNewssucess:^{
        
    } fail:^(int code, NSString * _Nonnull msg) {
        
    } inputStr:richStr];
    
}

//MARK:用户自己离开窗口
-(void)backAction:(UIButton *)btn{
    [self clearAllLogic];
    [self cleanALLObserver];
    WS(weakSelf);
    if (isNeedDelay==1) {
        [[SendLogicHandle keySendLoginHandle]sendDifferentMessaeWith:SDK_CHAT_OFFLINE chatModel:self.buildModel myModel:self.myModel contentType:@"text" msg:@"" sucess:^{
            [weakSelf dismissFromParentVC];
        } fail:^(int code, NSString * _Nonnull msg) {
            if (code==20006) {
                [weakSelf dismissFromParentVC];
            }
        }];
    }else{
        [self.showVC dismissFromParentVC];
        [weakSelf dismissFromParentVC];
        
    }
}

-(void)clearAllLogic{
    [self.showVC dismissFromParentVC];
    [[SendLogicHandle keySendLoginHandle]clearAllLogic];
    [[NSNotificationCenter defaultCenter]removeObserver:self];//移除所有通知
}

//把后台给的数据转换成cell需要的model
-(void)getCellDataFromHistory:(NSArray*)history{
    history=[[history reverseObjectEnumerator]allObjects];//倒序排列
    for (int i=0; i<history.count; i++) {
        WelcomeJsonhistoryMsgData*hisModel = history[i];
        NSTimeInterval sendTime=[GetChatTime getTimeStampFrom:hisModel.timeStr];
        
        if ([hisModel.isWelcome isEqualToString:@"1"]){
            NSString*historyMsg=hisModel.msg;
            BOOL isSelf=NO;
            if ([historyMsg containsString:@"<"]&&[historyMsg containsString:@"</"]) {
                MantisWelcomeImgModel*welModel = [MantisWelcomeImgModel new];
                welModel.isMyself=isSelf;
                welModel.historyModel=hisModel;
                welModel.sendTime=sendTime;
                if ([hisModel.say_from isEqualToString:@"A"]) {
                    welModel.agent=self.buildModel.payload.agent;//咨询师信息
                    welModel.imgUrl=self.avaterURL;
                }
                [self.dataArr addObject:welModel];
            }else{
                MantisTextCellData*textModel=[MantisTextCellData new];
                textModel.isMyself=isSelf;
                textModel.historyModel=hisModel;
                textModel.content=hisModel.msg;
                textModel.sendTime=sendTime;
                if ([hisModel.say_from isEqualToString:@"A"]) {
                    textModel.agent=self.buildModel.payload.agent;//咨询师信息
                    textModel.imgUrl=self.avaterURL;
                }
                [self.dataArr addObject:textModel];
            }
            
        }else if ([hisModel.type isEqualToString:@"text"]) {
            
            BOOL isSelf=[hisModel.say_from isEqualToString:@"V"]?YES:NO;
            
            NSString*historyMsg = hisModel.msg;
            if ([historyMsg containsString:@"label"]) {
                NSDictionary*subDic =historyMsg.mj_JSONObject;
                MantisTextCellSubContentData*subData = [MantisTextCellSubContentData mj_objectWithKeyValues:subDic];
                subData.isMyself=isSelf;
                subData.historyModel=hisModel;
                subData.sendTime=sendTime;
                if ([hisModel.say_from isEqualToString:@"A"]) {
                    subData.agent=self.buildModel.payload.agent;//咨询师信息
                    subData.imgUrl=self.avaterURL;
                }
                [self.dataArr addObject:subData];
            }else{
                
                if (([historyMsg containsString:@"<"]&&[historyMsg containsString:@"</"])||[historyMsg containsString:@"<img"]) {//咨询师或者机器人发送的富文本消息
                    MantisRichTextModel*richModel = [MantisRichTextModel new];
                    richModel.contentSize = [richModel contentSizefromMsg:historyMsg];
                    richModel.richStr = [richModel richStrFrom:historyMsg];
                    richModel.isMyself=isSelf;
                    richModel.sendTime=sendTime;
                    richModel.content=historyMsg;
                    if ([hisModel.say_from isEqualToString:@"A"]) {
                        richModel.agent=self.buildModel.payload.agent;//咨询师信息
                        richModel.imgUrl=self.avaterURL;
                    }
                    [self.dataArr addObject:richModel];
                    
                }else
                {
                    MantisTextCellData*textModel=[MantisTextCellData new];
                    textModel.isMyself=isSelf;
                    textModel.historyModel=hisModel;
                    textModel.sendTime=sendTime;
                    if ([hisModel.say_from isEqualToString:@"A"]) {
                        textModel.agent=self.buildModel.payload.agent;//咨询师信息
                        textModel.imgUrl=self.avaterURL;
                    }
                    
                    NSString*historyMsg =hisModel.msg;
                    if ([historyMsg containsString:@"src"]) {//含有表情
                        textModel.isHasEmoji=YES;
                        textModel.contentRichStr =[self.inputView getEmojiMessageStr:historyMsg];
                        textModel.inputStr=[self.inputView getEmojiMessage:historyMsg];
                    }else{
                        textModel.content=hisModel.msg;
                    }
                    
                    [self.dataArr addObject:textModel];
                    
                }
                
            }
            
        }else if([hisModel.type isEqualToString:@"IMG"]){
            
            BOOL isSelf=[hisModel.say_from isEqualToString:@"V"]?YES:NO;
            
            NSString*contentStr=hisModel.msg;
            if ([contentStr containsString:@"emojiImg"])
            {
                MantisTextCellData*textModel=[MantisTextCellData new];
                textModel.isMyself=isSelf;
                textModel.historyModel=hisModel;
                if ([hisModel.say_from isEqualToString:@"A"]) {
                    textModel.agent=self.buildModel.payload.agent;//咨询师信息
                    textModel.imgUrl=self.avaterURL;
                }
                textModel.sendTime=sendTime;
                textModel.isHasEmoji=YES;
                textModel.contentRichStr =[self.inputView getEmojiMessageStr:contentStr];
                textModel.inputStr=[self.inputView getEmojiMessage:contentStr];
                [self.dataArr addObject:textModel];
                
            }else{
                
                MantisImageMessageCellData*textModel=[MantisImageMessageCellData new];
                textModel.isMyself=isSelf;
                textModel.historyModel=hisModel;
                textModel.sendTime=sendTime;
                if ([hisModel.say_from isEqualToString:@"A"]) {
                    textModel.agent=self.buildModel.payload.agent;//咨询师信息
                    textModel.imgUrl=self.avaterURL;
                }
                textModel.content=hisModel.msg;
                [self.dataArr addObject:textModel];
            }
            
        }
        
    }
    [self refreshHistoryCellData];
    
}

//判断是否对话已经结束
-(BOOL)judgeChatIsHasEnd:(NSArray*)history{
    BOOL isEnd=NO;
    history=[[history reverseObjectEnumerator]allObjects];//倒序排列
    for (int i=0; i<history.count; i++) {
        WelcomeJsonhistoryMsgData*hisModel = history[i];
        if ([hisModel.msg containsString:@"CODE_ON_NAME_CLARIFY"]) {
            isEnd=YES;
            break;
        }
    }
    
    return  isEnd;
    
}


//MARK:机器人拉取追问
-(void)askRobotNews{
    WS(weakSelf);
    if ([self.obserVerisAsk isEqualToString:@"0"]) {//咨询师不需要拉取
        return;
    }
    
    if (self.isBall) {
        return;//球不在访客手里
    }
    
    if (askCount==0) {//拉取次数超限
        return;
    }
    
    //输入完成60s以后
    [MantisGCDTimer delayTime:60.0f withBlock:^{
        NSTimer*timer=[NSTimer scheduledTimerWithTimeInterval:10.0f repeats:YES block:^(NSTimer * _Nonnull timer) {
            MantisTextCellData*cellData= [SendComLogicHandle sendDifferentMessaeWith:SDK_SEND_AUTO_REQ chatModel:weakSelf.buildModel myModel:weakSelf.myModel contentType:@""];
            [[SendLogicHandle keySendLoginHandle] sendChatMesage:cellData.innerMessage sucess:^{
                
            } fail:^(int code, NSString * _Nonnull msg) {
                
            }];
            askCount--;
        }];
        [weakSelf.timerArr addObject:timer];
    }];
}

-(void)dealloc{
    [self clearAllLogic];
    [self cleanALLObserver];
    NSLog(@"%@释放了",NSStringFromClass([self class]));
}

-(void)cleanALLObserver{
    [self hiddenNetAndLoadingView];
    [self removeAllTimer];//移除掉所有计时器
    [self.view endEditing:YES];
    [[NSNotificationCenter defaultCenter]removeObserver:self];//移除所有通知
}
//移除掉所有计时器
-(void)removeAllTimer{
    NSInteger timerCount =self.timerArr.count;
    if (timerCount>0) {
        for (int i=0; i<self.timerArr.count; i++) {
            NSTimer *timer = self.timerArr[i];
            [timer invalidate];
            timer=nil;
            
        }
    }
}

-(NSMutableArray *)timerArr{
    if (!_timerArr) {
        _timerArr=[NSMutableArray new];
    }
    return _timerArr;
}


-(void)retryNews:(NSNotification*)notice{
    NSDictionary*dic=notice.userInfo;
    MantisCellBaseModel*cellData=dic[@"cellData"];
    cellData.isShowError=NO;
    [self sendChatMesageAndUpdateView:cellData];
}

//登录成功
-(void)loginSucess:(NSNotification*)notice{
    NSLog(@"登录腾讯云成功了");
}

//登录失败
-(void)loginFail:(NSNotification*)notice{
    NSLog(@"登录腾讯云失败了");
    [self leaveLine];
    
}


-(void)hasReceiveNewMessage:(NSArray *)msgs withMyModel:(MatinsIMinitModel *)myModel withConfig:(nonnull ConnectConfigModel *)configmodel{
    WS(weakSelf);
    weakSelf.myModel=myModel;
    weakSelf.configModel=configmodel;
    weakSelf.avaterURL=weakSelf.myModel.mbAgentIcon;
    [SendLogicHandle keySendLoginHandle].myModel=myModel;//保存初始化值
    
    TIMMessage*message=msgs.lastObject;
    int cnt = [message elemCount];
    for (int i = 0; i < cnt; i++) {
        TIMElem * elem = [message getElem:i];
        if ([elem isKindOfClass:[TIMCustomElem class]]) {
            TIMCustomElem * text_elem = (TIMCustomElem * )elem;
            NSData*data=text_elem.data;
            NSDictionary*dic =[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
            WelcomeJsonData*dicModel =[WelcomeJsonData mj_objectWithKeyValues:dic];
            WelComeJsonResponse*payload=dicModel.payload;
            NSLog(@"dic---%@",dic);
            NSString*type=dicModel.type;
            
            if ([type isEqualToString:ON_CHAT])
            {
                weakSelf.isCancleWelcome=@"1";//咨询师回话了停止发送欢迎语
                weakSelf.navView.backLabel.text=@"";
                weakSelf.obserVerisAsk=[payload.isRobot isEqualToString:@"Y"]?@"1":@"0";//标记聊天身份
                if ([payload.complete isEqualToString:@"Y"]) {
                    [weakSelf askRobotNews];//向机器人询问消息
                }
                BOOL isSelf=NO;
                //                weakSelf.navView.backLabel.text=[NSString stringWithFormat:@"%@正在与您对话",self.buildModel.payload.agent.display_name];
                if (![payload.content containsString:@"additionMsg"]) {
                    
                    MantisTextCellData*cellData=[ReceiveLogicHandle combineWelcomJsonModel:payload.content.mj_JSONData];
                    cellData.agent=self.buildModel.payload.agent;
                    NSString*content=payload.content;
                    cellData.sendTime=payload.timestamp;
                    if([payload.type isEqualToString:@"IMG"]){
                        
                        if ([content containsString:@"emojiImg"])
                        {
                            cellData.isHasEmoji=YES;
                            cellData.contentRichStr =[weakSelf.inputView getEmojiMessageStr:content];
                            cellData.inputStr=[weakSelf.inputView getEmojiMessage:content];
                            [weakSelf.dataArr addObject:cellData];
                            
                        }else
                        {
                            MantisImageMessageCellData*textModel=[MantisImageMessageCellData new];
                            textModel.isMyself=isSelf;
                            textModel.content=content;
                            textModel.agent=weakSelf.buildModel.payload.agent;
                            [weakSelf.dataArr addObject:textModel];
                        }
                        
                    }else{
                        if (([content containsString:@"<"]&&[content containsString:@"</"])||[content containsString:@"<img"]) {//富文本
                            MantisRichTextModel*richModel = [MantisRichTextModel new];
                            richModel.isMyself=NO;
                            richModel.agent=self.buildModel.payload.agent;
                            richModel.richStr = [richModel richStrFrom:content];
                            richModel.contentSize = [richModel contentSizefromMsg:content];
                            richModel.content=content;
                            [weakSelf.dataArr addObject:richModel];
                            
                        }else{
                            
                            if ([content containsString:@"emojiImg"])//表情
                            {
                                cellData.isHasEmoji=YES;
                                cellData.contentRichStr =[weakSelf.inputView getEmojiMessageStr:content];
                                cellData.inputStr=[weakSelf.inputView getEmojiMessage:content];
                                cellData.isMyself=isSelf;
                                cellData.agent=weakSelf.buildModel.payload.agent;
                                [weakSelf.dataArr addObject:cellData];
                            }else{
                                
                                //普通文本
                                cellData.content=payload.content;
                                cellData.isMyself=isSelf;
                                cellData.agent=weakSelf.buildModel.payload.agent;
                                [weakSelf.dataArr addObject:cellData];
                            }
                        }
                    }
                    
                    [weakSelf firstUPdataTableView];
                    
                }else if([payload.content containsString:@"additionMsg"]){
                    NSDictionary*dicJson=(NSDictionary*)payload.content;
                    NSDictionary*contentDic=dicJson.mj_keyValues;
                    MantisAcademicCellData *cellData = [MantisAcademicCellData new];
                    cellData.content=[MantisTextCellContentData mj_objectWithKeyValues:contentDic];
                    cellData.sendTime=payload.timestamp;
                    cellData.agent=self.buildModel.payload.agent;
                    [weakSelf.dataArr addObject:cellData];
                    [weakSelf firstUPdataTableView];
                    
                }
                
            }else if ([type isEqualToString:ON_KICK]){  //被踢下线
                
            }else if ([type isEqualToString:ON_CHAT_SUCC]){  //建立连接成功
                
                isNeedDelay=1;
                WelcomeJsonData*buildModel=[ReceiveLogicHandle buildConnetFromWelcom:dic];
                weakSelf.buildModel=buildModel;
                [SendLogicHandle keySendLoginHandle].buildModel=buildModel;//保存成功连接之后的值
                
                WelComeJsonResponse*responseModel=buildModel.payload;
                //                NSString*consultName=[NSString stringWithFormat:@"%@正在与您对话",buildModel.payload.agent.display_name];
                //                if (consultName.length>0) {
                //                    weakSelf.navView.backLabel.text=consultName;
                if (buildModel.payload.agent.img.length>0) {
                    weakSelf.avaterURL=buildModel.payload.agent.img;//头像url
                }
                
                //                }
                NSLog(@"已经成功建立连接");
                [weakSelf hiddenNetAndLoadingView];//隐藏转圈
                [weakSelf.welComesArr removeAllObjects];
                weakSelf.welComesArr =[ReceiveLogicHandle getWelcomeModelFrom:dic];
                
                if (weakSelf.myModel.mbPromTxt.length>0) {//开场语
                    weakSelf.headView.text=self.myModel.mbPromTxt;
                }else{
                    weakSelf.headView.frame=CGRectZero;
                    weakSelf.tableView.tableHeaderView=self.headView;
                }
                if (responseModel.historyMsg.count>0) {
                    [weakSelf getCellDataFromHistory:responseModel.historyMsg];
                    [weakSelf.historyArr addObjectsFromArray:responseModel.historyMsg];//标记历史消息
                    if ([self judgeChatIsHasEnd:responseModel.historyMsg]) {
                        weakSelf.headView.frame=CGRectZero;
                        weakSelf.tableView.tableHeaderView=weakSelf.headView;
                    }
                    
                    return;
                }
                
                
                CGFloat sum=0;
                __block int timerTotalCount =(int)weakSelf.welComesArr.count;
                
                for (int i=0;i<weakSelf.welComesArr.count; i++) {
                    
                    WelcomeJsonwelcomesArrData*welComeModel =weakSelf.welComesArr[i];
                    NSTimeInterval gap=welComeModel.gap.doubleValue;
                    sum+=gap;
                    
                    weakSelf.myTimer=  [NSTimer scheduledTimerWithTimeInterval:sum repeats:NO block:^(NSTimer * _Nonnull timer) {
                        if ([weakSelf.isCancleWelcome isEqualToString:@"1"]) {
                            return ;
                        }
                        [MantisGCDTool mainBlock:^{
                            WelcomeJsonwelcomesArrData*welJsonModel=weakSelf.welComesArr[i];
                            if ([welJsonModel.msg containsString:@"additionMsg"]||[welJsonModel.msg containsString:@"<p>"]) {//选择性欢迎语
                                MantisWelcomeImgModel*webModel=[MantisWelcomeImgModel new];
                                WelcomeJsonhistoryMsgData*historyModel=[WelcomeJsonhistoryMsgData new];
                                historyModel.msg=welJsonModel.msg;
                                webModel.historyModel=historyModel;
                                webModel.imgUrl=weakSelf.avaterURL;
                                [weakSelf.dataArr addObject:webModel];//添加选择性欢迎语
                            }else{
                                MantisTextCellData *cellData=[ReceiveLogicHandle combineWelcomJsonModel:welJsonModel.mj_JSONData];
                                cellData.content=welJsonModel.msg;
                                cellData.imgUrl=weakSelf.avaterURL;
                                cellData.agent=weakSelf.buildModel.payload.agent;
                                [weakSelf.dataArr addObject:cellData];//普通文本欢迎语
                            }
                            
                            [weakSelf firstUPdataTableView];
                            timerTotalCount--;
                            NSLog(@"开始发送欢迎语了");
                            if (i>0) {
                                [[SendLogicHandle keySendLoginHandle]sendDifferentMessaeWith:SDK_WELCOME_MSG chatModel:self.buildModel myModel:self.myModel  contentType:@"text" msg:welJsonModel.msg sucess:^{
                                    
                                } fail:^(int code, NSString * _Nonnull msg) {
                                    
                                }];
                                
                                
                            }
                            [weakSelf.timerArr addObject:weakSelf.myTimer];
                            
                        } ];
                        
                    }];
                    
                }
            }else if ([type isEqualToString:ON_CHAT_FAIL]){  //未成功收到消息,跳转留言界面
                [weakSelf showHiddenoodView:nil];
                
            }else if ([type isEqualToString:ON_TRANSFER]){//转接
                WelcomeJsonData*transModel=[ReceiveLogicHandle buildConnetFromWelcom:dic];
                [weakSelf transFerTelephone:transModel];
            }else if ([type isEqualToString:ON_AGENT_LEAVE]){//咨询师离线
                [weakSelf leaveLine];
            }
        }
    }
    
}
//接收到账号互踢、断网重连、账号过期代理
-(void)hasReceiveUserStautsChange:(NSString *)status{
    WS(weakSelf);
    if ([status isEqualToString:USER_KICK_OFF])
    {
        
        if ([weakSelf.inputView.textField isFirstResponder]) {//如果是第一响应，先取消第一响应
            [weakSelf.inputView.textField resignFirstResponder];
        }
        ShowMessageViewController*showVC =[[ShowMessageViewController alloc]initWithArr:@[@"退出"]];
        weakSelf.showVC=showVC;
        showVC.messageLabel.text=@"您的账号在另一台设备登录，您已被踢下线";
        showVC.cancleBlock  = ^{
            [weakSelf.showVC dismissFromParentVC];
            [weakSelf.navigationController popViewControllerAnimated:YES];
        };
        
        [showVC showCurrentVC:weakSelf.navigationController];
        
    }else
    {
        [[ChatHandleCommonLogic new]handleChatVCReceiveTecentDelegate:status baseVC:weakSelf];
        
    }
}
//MARK:咨询师离线
-(void)leaveLine{
    if (self.isHasJump) {
        return;
    }
    
    [self cleanALLObserver];
    MantisLeaveMessageViewController*leaveMessage =[MantisLeaveMessageViewController new];
    [self showViewController:leaveMessage sender:nil];
    self.isHasJump=YES;//标记已经跳转
}

//MARK:转接
-(void)transFerTelephone:(WelcomeJsonData*)transModel{
    
    WelComeJsonResponse*responseModel=transModel.payload;
    
    [self setLoadingAnimationFrame:self.chatView.frame imgArr:self.imgArr];//转圈
    self.loadingView.contentLB.text=@"正在转接中";
    if (self.dataArr.count>0) {
        [self.dataArr removeAllObjects];
    }
    
    if (self.welComesArr.count>0) {
        [self.welComesArr removeAllObjects];
    }
    
    self.myModel.defaultSvgId=@(responseModel.newServiceGroupId).stringValue;
    
    [[MantisSDKTool keyManitsSDKTool]sendConfigMessage:self.configModel initModel:self.myModel];//重新连接
    
}

//长时间未建立连接，跳转留言
-(void)showHiddenoodView:(NSNotification*)notice{
    WS(weakSelf);
    if (isNeedDelay==0&&!self.isHasJump) {
        [weakSelf hiddenNetAndLoadingView];
        ShowMessageViewController*showVC =[[ShowMessageViewController alloc]initWithArr:@[@"进入留言",@"重连"]];
        self.showVC=showVC;
        showVC.messageLabel.text=@"与客服建立连接失败";
        showVC.cancleBlock = ^{
            [weakSelf.showVC dismissFromParentVC];
            [weakSelf leaveLine];
            
        };
        weakSelf.showVC.ensureBlock  = ^{
            [weakSelf.showVC dismissFromParentVC];
            [weakSelf setLoadingAnimationFrame:weakSelf.chatView.frame imgArr:weakSelf.imgArr];//转圈
            weakSelf.loadingView.contentLB.text=weakSelf.loadingText.length>0? weakSelf.loadingText: @"正在与客服重新连接";
            
            MatinsIMinitModel*myModel=[MantisSDKTool keyManitsSDKTool].myModel;
            weakSelf.myModel=myModel;
            if ([NSString isBlankString:myModel.probeId]) {
                [[MantisSDKTool keyManitsSDKTool]prepareStartChatWith:weakSelf.userModel sucess:^(MatinsIMinitModel * _Nonnull myModel, ConnectConfigModel * _Nonnull cofigModel) {
                    
                } fail:^(NSError * _Nonnull error) {
                    
                }];
            }
            [[MantisSDKTool keyManitsSDKTool] sendConfigMessage:weakSelf.configModel initModel:weakSelf.myModel];
            
        };
        [showVC showCurrentVC:self];
    }
    
}
- (BOOL)shouldAutorotate{
    return NO;
}
-(void)showCurrentVC:(UIViewController*)baseVC{
    WS(weakSelf);
    [baseVC addChildViewController:self];
    [baseVC.view addSubview:self.view];
    weakSelf.view.frame=CGRectMake(0, weakSelf.view.jk_height, weakSelf.view.jk_width, weakSelf.view.jk_height);
    [UIView animateWithDuration:.2 animations:^{
        weakSelf.view.frame=CGRectMake(0, 0, weakSelf.view.jk_width, weakSelf.view.jk_height);
    }];
}

-(void)dismissFromParentVC{
    
    WS(weakSelf);
    [UIView animateWithDuration:.1 animations:^{
        weakSelf.view.frame=CGRectMake(0, weakSelf.view.jk_height, weakSelf.view.jk_width,  weakSelf.view.jk_height);
    } completion:^(BOOL finished) {
        [weakSelf.view removeFromSuperview];
        [weakSelf removeFromParentViewController];
    }];
}
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
    
    UIView*tableView = touch.view;
    if(tableView==self.blackView){
        return  YES;
    }
    return  NO;
}
//MARK:适配屏幕比例
-(float)screenRate{
    float rate =1.0;
    
    if (self.probeModel.mbIframeHeight>0&&self.userModel.isAutoFrame==NO) {
        rate =self.probeModel.mbIframeHeight/100.0;
    }
    
    if (self.probeModel.mbAutoIframeHeight>0&&self.userModel.isAutoFrame==YES) {
        rate =self.probeModel.mbAutoIframeHeight/100.0;
    }
    
    return  rate;
}
//获取探头信息
-(void)getLatestProbeData{
        WS(weakSelf);
        [[MantisSDKTool keyManitsSDKTool]requstProbeinfo:^(MatinsIMinitModel * _Nonnull myModel, ConnectConfigModel * _Nonnull cofigModel) {
            [weakSelf.navView reloadNavView:myModel];
        }];

}


/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
